<!-- eslint-disable vue/valid-v-for -->
<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" :title="pageTitle" />
    </div>
    <n-form
      :model="formValues"
      :rules="rules"
      label-placement="left"
      ref="formRef"
      class="py-4"
      :label-width="80"
    >
      <n-card
        :bordered="false"
        title="基本信息"
        class="proCard"
        size="large"
        :segmented="{ content: true }"
      >
        <n-grid cols="2" responsive="screen">
          <n-grid-item offset="0">
            <n-form-item label="文章标题" path="articleTitle">
              <n-input placeholder="请输入文章标题" v-model:value="formValues.articleTitle" />
            </n-form-item>

            <n-form-item label="文章封面" path="cover">
              <BasicUpload
                :data="{ scene: 'article' }"
                name="file"
                :width="100"
                :height="100"
                :maxSize="2"
                :maxNumber="1"
                :max="1"
                :multiple="true"
                v-model:value="uploadList"
                helpText="单个文件不超过2MB，最多只能上传1张图片"
              />
            </n-form-item>
          </n-grid-item>
        </n-grid>
      </n-card>
      <n-card
        :bordered="false"
        title="文章详情"
        class="mt-2 proCard"
        size="large"
        :segmented="{ content: true }"
      >
        <n-grid cols="2" responsive="screen">
          <n-grid-item offset="0" span="2">
            <BasicEditor height="600" v-model="formValues.articleContent" />
          </n-grid-item>
        </n-grid>
      </n-card>
      <div class="tools-block" ref="toolsRef">
        <n-card class="mt-2 proCard tools" tag="div" hoverable>
          <n-space justify="center" style="">
            <n-button
              type="primary"
              size="large"
              :loading="formBtnLoading"
              @click="formArticleSubmit"
              >提交</n-button
            >
            <n-button size="large" @click="resetArticleFrom">重置</n-button>
          </n-space>
        </n-card>
      </div>
      <div class="white-block" ref="containerRef"></div>
    </n-form>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import { useMessage, NButton, TreeSelectOption } from 'naive-ui';
  import { BasicResponseModel, saveArticle, updateArticle, getArticle } from '@/api/site/article';
  import { ResultEnum } from '@/enums/httpEnum';
  import BasicEditor from '@/components/Editor/BasicEditor.vue';
  import { useRoute } from 'vue-router';
  const rules = {
    // goodsClassifyId: {
    //   required: true,
    //   message: '请选择商品分类',
    //   trigger: 'blur',
    //   type: 'number',
    //   validator: (_rule: any, value: number) => {
    //     if (value === 0) {
    //       return Promise.reject('请选择商品分类');
    //     } else {
    //       return Promise.resolve();
    //     }
    //   },
    // },
    articleTitle: {
      required: true,
      message: '请输入文章标题',
      trigger: 'blur',
    },
  };

  interface Article {
    id: number;
    articleClassifyId: number;
    articleTitle: string;
    cover: string;
    articleContent: string;
    status: number;
    sort: number;
    updateTime: number;
    createTime: number;
  }
  const formValues: Article = reactive({
    id: 0,
    articleClassifyId: 0,
    articleTitle: '',
    cover: '',
    articleContent: '',
    status: 0,
    sort: 0,
    updateTime: 0,
    createTime: 0,
  });
  const formValuesBak = { ...formValues };
  const containerRef = ref<HTMLElement | undefined>(undefined);
  const toolsRef = ref<HTMLElement | undefined>(undefined);
  const uploadList = ref<string[]>([]);
  console.log(uploadList);
  const formBtnLoading = ref(false);
  const formRef: any = ref(null);
  const message = useMessage();

  const route = useRoute();

  const pageTitle = ref('添加文章');

  const isEdit = ref(false);

  onMounted(async () => {
    // 动态设置工具条宽度
    let width = containerRef.value?.offsetWidth;
    toolsRef.value!.style.width = width + 'px';
    const title = route.params.title?.toString();
    const articleId = route.params.id;
    pageTitle.value = title === undefined ? '添加文章' : title;
    if (articleId) {
      isEdit.value = true;
      let response: BasicResponseModel<any>;
      response = await getArticle({ id: articleId });
      const articleInfo = response.result;
      uploadList.value[0] = articleInfo.cover;
      //console.log(uploadList.value);
      Object.assign(formValues, articleInfo);
      Object.assign(formValuesBak, articleInfo);
    }
  });

  function formArticleSubmit(_e: { preventDefault: () => void }) {
    _e.preventDefault();
    formBtnLoading.value = true;
    formValues.cover = uploadList.value[0];
    console.log(formValues);
    formRef.value.validate(async (errors: any) => {
      if (!errors) {
        let response: BasicResponseModel<any>;
        if (formValues.id === 0) {
          response = await saveArticle(formValues);
        } else {
          response = await updateArticle(formValues);
        }
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
        } else {
          message.error(msg);
        }
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  function resetArticleFrom() {
    // 清空
    Object.assign(formValues, formValuesBak);
  }
</script>

<style lang="less" scoped>
  .tools-block {
    position: fixed;
    bottom: 10px;
    z-index: 10;
    //width: 100%;
  }

  .white-block {
    height: 72px;
    width: 100%;
  }
</style>
